package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XMLMapperBuilder {
    private Configuration configuration;
    public XMLMapperBuilder(Configuration configuration){
        this.configuration=configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        List<String> nodes = Arrays.asList("//select", "//update", "//delete", "//insert");
        for (String node : nodes) {
            List<Element> list = rootElement.selectNodes(node);
            for (Element element : list) {
                String id = element.attributeValue("id");
                MappedStatement mappedStatement=new MappedStatement();
                mappedStatement.setId(id);
                mappedStatement.setParameterType(element.attributeValue("paramterType"));
                mappedStatement.setResultType(element.attributeValue("resultType"));
                mappedStatement.setSql(element.getTextTrim());
                mappedStatement.setSqlType(node);
                configuration.getMappedStatementMap().put(namespace+"."+id,mappedStatement);
            }
        }
    }
}
